<template>
  <view class="form-section">
    <view class="section-header" @click="toggleCollapse">
      <text class="section-title">5. 风险和并发症</text>
      <IconFont :name="isExpanded ? 'arrow-up' : 'arrow-down'" size="10" color="#8bc34a" :class="['transition-transform duration-200', isExpanded ? 'rotate-180' : 'rotate-0']" />
    </view>
    <view v-show="isExpanded" class="section-content space-y-[16rpx]">
      <!-- 新增项目 -->
      <view class="border-2 border-dashed border-gray-300 rounded-[12rpx] p-[16rpx]">
        <text class="text-[24rpx] font-medium text-gray-600 block mb-[12rpx]">新增项目</text>
        <ItemWithImagesCard
          v-for="(_item, index) in formData?.comprehensiveHealthAssessment?.complicationsAndRisks?.newItems"
          :key="index"
          :model-value="getItemValue(index)"
          @update:model-value="(value) => updateItemValue(index, value)"
          :show-delete="true"
          title-label="项目名称"
          description-label="项目描述"
          :dict-code="(_item as any)?.dictCode || ''"
          :description-rows="2"
          border-color="border-orange-300"
          @delete="removeNewItem('complicationsAndRisks.newItems', index)"
          class="mb-[16rpx]"
        >
          <template #header>
            <!-- 医院部门选择器 -->
            <view class="hospital-selector" @click="() => showDirectoryPopup('complicationsAndRisks.newItems', index)">
              <view class="selector-content">
                <text class="selector-text">
                  {{ getSelectorText("complicationsAndRisks.newItems", index) }}
                </text>
                <text class="selector-arrow">▼</text>
              </view>
            </view>

            <!-- 疾病选择器 -->
            <view class="disease-selector mb-2" @click="() => showDiseasePopupHandler('complicationsAndRisks.newItems', index)">
              <view class="selector-content">
                <text class="selector-text">
                  {{ getDiseaseSelectorText("complicationsAndRisks.newItems", index) }}
                </text>
                <text class="selector-arrow">▼</text>
              </view>
            </view>

            <!-- 📊 评估量表 -->
            <view class="assessment-content mb-[24rpx]">
              <view class="assessment-grid">
                <!-- 认知功能评估 -->
                <view class="scale-category">
                  <view class="category-header">
                    <text class="category-icon">🧠</text>
                    <text class="category-title">认知功能评估</text>
                  </view>
                  <view class="scale-items">
                    <view class="scale-item">
                      <text class="item-label">MMSE评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">MoCA评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">ADL评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                  </view>
                </view>

                <!-- 心理状态评估 -->
                <view class="scale-category">
                  <view class="category-header">
                    <text class="category-icon">💭</text>
                    <text class="category-title">心理状态评估</text>
                  </view>
                  <view class="scale-items">
                    <view class="scale-item">
                      <text class="item-label">GDS评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">HADS评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">PHQ-9评分</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                  </view>
                </view>

                <!-- 疾病风险评估 -->
                <view class="scale-category">
                  <view class="category-header">
                    <text class="category-icon">🏥</text>
                    <text class="category-title">疾病风险评估</text>
                  </view>
                  <view class="scale-items">
                    <view class="scale-item">
                      <text class="item-label">卒中风险</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">感染风险</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                    <view class="scale-item">
                      <text class="item-label">低血糖风险</text>
                      <view class="input-placeholder">输入文字</view>
                    </view>
                  </view>
                </view>

                <!-- 综合评分 -->
                <view class="scale-category highlight">
                  <view class="category-header">
                    <text class="category-icon">📈</text>
                    <text class="category-title">综合评分</text>
                  </view>
                  <view class="scale-items">
                    <view class="scale-item highlight-item">
                      <text class="item-label">总体健康评分</text>
                      <view class="input-placeholder highlight-input">输入文字</view>
                    </view>
                    <view class="scale-item highlight-item">
                      <text class="item-label">护理等级</text>
                      <view class="input-placeholder highlight-input">输入文字</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </template>
        </ItemWithImagesCard>

        <view class="flex gap-[12rpx]">
          <nut-button type="primary" size="small" @click="addNewItem('complicationsAndRisks.newItems')" class="flex-1"> 新增自定义项目 </nut-button>
          <nut-button type="success" size="small" @click="addSystemItem('complicationsAndRisks.newItems', 'h_danger')" class="flex-1"> 新增常规项目 </nut-button>
        </view>
      </view>
    </view>

    <!-- 医院部门选择器弹窗 -->
    <HospitalDepartmentProjectSelector :visible="!!showPopup" @update:visible="(val) => (showPopup = val ? showPopup : false)" @close="closeDirectoryPopup" @confirm="handleSelectorConfirm" />

    <!-- 疾病选择弹窗 -->
    <DiseaseSelector
      :visible="!!showDiseasePopup"
      :project-id="showDiseasePopup ? getNestedValue(formData, `comprehensiveHealthAssessment.${showDiseasePopup.path}`)?.[showDiseasePopup.index]?.projectId : undefined"
      @update:visible="(val) => (showDiseasePopup = val ? showDiseasePopup : false)"
      @close="closeDiseasePopup"
      @confirm="handleDiseaseConfirm"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useMedicalRecordStore } from "@/store/modules/medicalRecord";
import ItemWithImagesCard from "@/components/ItemWithImagesCard.vue";
import HospitalDepartmentProjectSelector from "@/components/HospitalDepartmentProjectSelector.vue";
import DiseaseSelector from "@/components/DiseaseSelector.vue";
import { IconFont } from "@nutui/icons-vue-taro";

interface Props {
  isExpanded: boolean;
}

interface Emits {
  (e: "toggle"): void;
}

defineProps<Props>();
const emit = defineEmits<Emits>();

const toggleCollapse = () => {
  emit("toggle");
};

const medicalRecordStore = useMedicalRecordStore();
const formData = computed(() => medicalRecordStore.formData);

// 初始化检查
const initializeIfEmpty = () => {
  const items = (formData.value as any)?.comprehensiveHealthAssessment?.complicationsAndRisks?.newItems;
  if (!items || items.length === 0) {
    addSystemItem("complicationsAndRisks.newItems", "h_danger");
  }
};

// 获取项目值
const getItemValue = (index: number) => {
  return (formData.value as any)?.comprehensiveHealthAssessment?.complicationsAndRisks?.newItems?.[index] || {};
};

// 更新项目值
const updateItemValue = (index: number, value: any) => {
  const items = (formData.value as any)?.comprehensiveHealthAssessment?.complicationsAndRisks?.newItems;
  if (items && items[index]) {
    items[index] = value;
  }
};

// 选择器相关状态和方法
const showPopup = ref<{ path: string; index: number } | false>(false);
const showDiseasePopup = ref<{ path: string; index: number } | false>(false);

// 获取选择器显示文本
const getSelectorText = (path: string, index: number) => {
  const items = getNestedValue(formData.value, `comprehensiveHealthAssessment.${path}`);
  const item = items?.[index];
  const parts: string[] = [];
  if ((item as any)?.hospital) parts.push((item as any).hospital);
  if ((item as any)?.department) parts.push((item as any).department);
  if ((item as any)?.dept) parts.push((item as any).dept);
  if ((item as any)?.project) parts.push((item as any).project);

  if (parts.length) {
    return parts.join(" / ");
  }
  return "请选择机构/部门/科室/项目组";
};

// 获取疾病选择器显示文本
const getDiseaseSelectorText = (path: string, index: number) => {
  const items = getNestedValue(formData.value, `comprehensiveHealthAssessment.${path}`);
  const item = items?.[index];
  if ((item as any)?.disease) {
    return (item as any).disease;
  }
  return "请选择疾病（开发中）";
};

// 显示医院部门选择器
const showDirectoryPopup = (path: string, index: number) => {
  showPopup.value = { path, index };
};

// 关闭医院部门选择器
const closeDirectoryPopup = () => {
  showPopup.value = false;
};

// 处理医院部门选择确认
const handleSelectorConfirm = (data: any) => {
  if (showPopup.value) {
    const { path, index } = showPopup.value;
    const { hospital, team, department, project } = data;
    const items = getNestedValue(formData.value, `comprehensiveHealthAssessment.${path}`);
    const item = items?.[index];

    if (item) {
      if (hospital) (item as any).hospital = hospital.title || hospital.name;
      if (team) (item as any).department = team.title || team.name;
      if (department) (item as any).dept = department.title || department.name;
      if (project) {
        (item as any).project = project.title || project.name;
        (item as any).projectId = project.id || project.key;
      }
    }
  }
  showPopup.value = false;
};

// 显示疾病选择器
const showDiseasePopupHandler = (path: string, index: number) => {
  showDiseasePopup.value = { path, index };
};

// 关闭疾病选择器
const closeDiseasePopup = () => {
  showDiseasePopup.value = false;
};

// 处理疾病选择确认
const handleDiseaseConfirm = (disease: any) => {
  if (showDiseasePopup.value) {
    const { path, index } = showDiseasePopup.value;
    const items = getNestedValue(formData.value, `comprehensiveHealthAssessment.${path}`);
    const item = items?.[index];

    if (item) {
      if (disease.customItems) {
        // 处理自定义项目
        const customDiseaseName = disease.customItems.map((item: any) => item.title).join("、");
        (item as any).disease = customDiseaseName;
        (item as any).diseaseId = disease.id;
        (item as any).customDiseaseItems = disease.customItems;
      } else {
        // 处理标准疾病
        (item as any).disease = disease.name;
        (item as any).diseaseId = disease.id;
      }
    }
  }
  showDiseasePopup.value = false;
};

// 获取嵌套值的辅助函数
const getNestedValue = (obj: any, path: string) => {
  return path.split(".").reduce((current, key) => current?.[key], obj);
};

// 添加新项目（自定义项目，dict-code为空）
function addNewItem(path: string) {
  if (!medicalRecordStore.formData) {
    medicalRecordStore.initializeFormData();
  }

  const newItem: any = { title: "", description: "", images: [], dictCode: "" };
  medicalRecordStore.addNewItem(`comprehensiveHealthAssessment.${path}`, newItem);
}

// 添加系统项目（带dict-code）
function addSystemItem(path: string, dictCode: string) {
  if (!medicalRecordStore.formData) {
    medicalRecordStore.initializeFormData();
  }

  const newItem: any = { title: "", description: "", images: [], dictCode: dictCode };
  medicalRecordStore.addNewItem(`comprehensiveHealthAssessment.${path}`, newItem);
}

// 删除项目
function removeNewItem(path: string, index: number) {
  if (!medicalRecordStore.formData) {
    medicalRecordStore.initializeFormData();
  }

  medicalRecordStore.removeNewItem(`comprehensiveHealthAssessment.${path}`, index);
}

onMounted(() => {
  initializeIfEmpty();
});
</script>

<style scoped lang="scss">
.form-section {
  background: white;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-header {
  padding: 24rpx;
  background: #f8f9fa;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: background-color 0.2s;

  &:hover {
    background: #e9ecef;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-content {
  padding: 24rpx;
}

.assessment-content {
  .assessment-grid {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
  }

  .scale-category {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 16rpx;
    padding: 24rpx;
    border: 2rpx solid #e2e8f0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:active {
      transform: scale(0.98);
      box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.08);
    }

    &.highlight {
      background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%);
      border-color: #fb923c;
      box-shadow: 0 4rpx 16rpx rgba(251, 146, 60, 0.15);
    }

    .category-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      padding-bottom: 16rpx;
      border-bottom: 2rpx solid #e2e8f0;

      .category-icon {
        font-size: 36rpx;
        margin-right: 12rpx;
        filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.1));
      }

      .category-title {
        font-size: 30rpx;
        font-weight: 700;
        color: #1e293b;
        letter-spacing: 0.5rpx;
      }
    }

    .scale-items {
      display: flex;
      flex-direction: column;
      gap: 16rpx;

      .scale-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 24rpx;
        background: white;
        border-radius: 12rpx;
        border: 2rpx solid #e2e8f0;
        transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);

        &:active {
          transform: translateX(-2rpx);
          border-color: #cbd5e1;
          box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
        }

        &.highlight-item {
          background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%);
          border-color: #fb923c;
          box-shadow: 0 2rpx 8rpx rgba(251, 146, 60, 0.15);

          .item-label {
            color: #9a3412;
          }
        }

        .item-label {
          font-size: 28rpx;
          color: #334155;
          font-weight: 600;
          letter-spacing: 0.3rpx;
        }

        .input-placeholder {
          padding: 12rpx 24rpx;
          background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
          border: 2rpx solid #cbd5e1;
          border-radius: 10rpx;
          font-size: 26rpx;
          color: #64748b;
          min-width: 140rpx;
          text-align: center;
          font-weight: 500;
          transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);

          &:active {
            background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
            border-color: #94a3b8;
            transform: scale(0.96);
          }
        }

        .highlight-input {
          background: linear-gradient(135deg, #ffedd5 0%, #fed7aa 100%);
          border-color: #fb923c;
          color: #9a3412;
          font-weight: 700;
        }
      }
    }
  }
}

.hospital-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 24rpx;

  &:hover {
    border-color: #3b82f6;
  }

  &:active {
    opacity: 0.8;
  }

  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;

    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }

    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }

  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}

.disease-selector {
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  margin-bottom: 24rpx;

  &:hover {
    border-color: #3b82f6;
  }

  &:active {
    opacity: 0.8;
  }

  .selector-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;

    .selector-text {
      font-size: 28rpx;
      color: #374151;
      flex: 1;
    }

    .selector-arrow {
      font-size: 24rpx;
      color: #9ca3af;
      margin-left: 16rpx;
      transition: transform 0.2s ease;
    }
  }

  &:active .selector-arrow {
    transform: rotate(180deg);
  }
}
</style>
